<template>
	<view class="container">
		<!-- 头像上传 -->
		<view class="form-item avatar-item">
			<text class="label">头像</text>
			<view class="avatar-upload" @tap="chooseAvatar">
				<image 
					class="avatar" 
					:src="formData.avatar ? formData.avatar : api.BASE_URL + userInfo.avatar" 
					mode="aspectFill"
				></image>
				<text class="tip">点击更换头像</text>
			</view>
		</view>

		<!-- 用户ID -->
		<view class="form-item">
			<text class="label">用户ID</text>
			<view class="user-id-box">
				<text class="user-id">{{userInfo.user_id}}</text>
				<text class="copy-btn" @tap="copyUserId">复制</text>
			</view>
		</view>
		
		<!-- 用户名 -->
		<view class="form-item">
			<text class="label">用户名</text>
			<input 
				type="text"
				v-model="formData.username"
				:placeholder="userInfo.username"
				placeholder-class="placeholder"
			/>
		</view>
		
		
		
		<!-- 密码 -->
		<view class="form-item">
			<text class="label">修改密码</text>
			<input 
				type="password"
				v-model="formData.password"
				placeholder="不修改请留空"
				placeholder-class="placeholder"
			/>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-btn" @tap="handleSave">保存修改</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { api } from '@/utils/request'
import Storages from '@/utils/storages'

// 用户信息
const userInfo = ref({})

// 表单数据
const formData = ref({
	username: '',
	password: '',
	avatar: ''
})

// 获取用户信息
const getUserInfo = () => {
	const info = uni.getStorageSync(Storages.UserInfo.userInfo)
	if(info) {
		userInfo.value = info
	}
}

// 选择头像
const chooseAvatar = async () => {
	try {
		const res = await uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera']
		})
		formData.value.avatar = res.tempFilePaths[0]
	} catch(err) {
		console.error('选择图片失败', err)
	}
}

// 保存修改
const handleSave = async () => {
	// 构建请求参数
	const params = {
		user_id: userInfo.value.user_id
	}
	
	// 只添加修改的字段
	if(formData.value.username) {
		params.username = formData.value.username
	}
	if(formData.value.password) {
		params.password = formData.value.password
	}
	
	try {
		let responseData = null
		
		// 如果有头像上传
		if(formData.value.avatar) {
			await new Promise((resolve, reject) => {
				uni.uploadFile({
					url: api.BASE_URL + '/api/users/edit_user_info/',
					filePath: formData.value.avatar,
					name: 'avatar',
					formData: params,
					success: (uploadRes) => {
						const data = JSON.parse(uploadRes.data)
						if(data.code === 200) {
							responseData = data.data
							resolve(data)
						} else {
							reject(new Error(data.message))
						}
					},
					fail: reject
				})
			})
		} else {
			// 没有头像上传,直接发送请求
			const res = await api.request({
				url: '/api/users/edit_user_info/',
				method: 'POST',
				data: params
			})
			
			if(res.code !== 200) {
				throw new Error(res.message)
			}
			responseData = res.data
		}
		
		// 更新本地存储的用户信息
		const newUserInfo = {
			username: responseData.username,
			account: responseData.account,
			avatar: responseData.avatar,
			user_id: responseData.user_id,
			create_time: responseData.create_time,
			update_time: responseData.update_time
		}
		uni.setStorageSync(Storages.UserInfo.userInfo, newUserInfo)
		
		// 显示成功提示
		uni.showToast({
			title: '修改成功',
			icon: 'success'
		})
		
		// 返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
		
	} catch(err) {
		console.error('保存失败', err)
		uni.showToast({
			title: err.message || '保存失败',
			icon: 'none'
		})
	}
}

// 添加复制 user_id 的方法
const copyUserId = () => {
	uni.setClipboardData({
		data: userInfo.value.user_id.toString(),
		success: () => {
			uni.showToast({
				title: '已复制用户ID',
				icon: 'success'
			})
		}
	})
}

onMounted(() => {
	getUserInfo()
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 20rpx;
}

.form-item {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}
	
	input {
		font-size: 28rpx;
		color: #333;
	}
	
	.placeholder {
		color: #999;
	}
	
	&.avatar-item {
		.avatar-upload {
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				margin-bottom: 20rpx;
			}
			
			.tip {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
}

.user-id-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
	
	.user-id {
		font-size: 28rpx;
		color: #333;
		max-width: 400rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.copy-btn {
		font-size: 24rpx;
		color: #ff6b6b;
		padding: 6rpx 20rpx;
		border: 1rpx solid #ff6b6b;
		border-radius: 24rpx;
		margin-left: 20rpx;
		flex-shrink: 0;
		
		&:active {
			opacity: 0.7;
		}
	}
}

.save-btn {
	background: #ff6b6b;
	color: #fff;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	border-radius: 44rpx;
	font-size: 32rpx;
	margin-top: 60rpx;
	
	&:active {
		opacity: 0.8;
	}
}
</style>
